package org.example.serialize;

import java.io.*;

public class Person implements Serializable {
    private static final long serialVersionUID = 1L; // 显式声明serialVersionUID，保证版本兼容性
    private String name;
    private int age;
    private boolean man;
    private boolean h;
    private boolean h2;

    private transient String address; // transient关键字表示该字段不需要序列化

    public Person(String name, int age, boolean man, String address) {
        this.name = name;
        this.age = age;
        this.man = man;
        this.address = address;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", man=" + man +
                ", h=" + h +
                ", h2=" + h2 +
                ", address=" + address +
                '}';
    }

    public static void serialize() throws IOException {
        Person person = new Person("张三", 18, true, "地址-不需要被序列化的字段");
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))){
            oos.writeObject(person);
        }
    }

    public static void deserialize() throws IOException, ClassNotFoundException {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))){
            Person person = (Person) ois.readObject();
            System.out.println("反序列化得到的对象：" + person); // 反序列化得到的对象：Person{name='张三', age=18}
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Person.serialize();
        Person.deserialize();
    }
}
